package com.study.zzedu.ui.exercise.activity;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.study.zzedu.R;
import com.study.zzedu.ui.exercise.view.NoScrollGridView;
import com.study.zzedu.utils.AppConstant;
import com.study.zzedu.utils.LogUtil;
import com.study.zzedu.utils.OkHttpUtils;
import com.study.zzedu.utils.Utils;

import org.json.JSONArray;
import org.json.JSONObject;

/**
 * @version 1.0
 * @author hzc
 * @date 2015-6-24
 */

public class ScantronItemActivity extends Activity {
	LocalBroadcastManager mLocalBroadcastManager;
	//int[] mIds = new int[count];
	NoScrollGridView gv;
	public static MyAdapter adapter;

	private String answerStr="",totalTime="";
	private TextView tv_paper_score,tv_timer_result,tv_exercise_again,tv_btn_back;
	private RelativeLayout btn_back;
	@Override
	protected void onCreate(@Nullable Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		String answer = getIntent().getStringExtra("answer");
		try {
			JSONObject job = new JSONObject(answer);
			//subjectCodes = job.getString("subjectCodes");
			answerStr = job.getString("answerStr");
			totalTime = job.getString("totalTime");
		}catch (Exception e){
			e.toString();
		}
		setContentView(R.layout.pager_item_scantron);
		initView();
		initData();

		LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(this);
		IntentFilter filter = new IntentFilter();
		filter.addAction(AppConstant.ACTION_EVENT_UPDATA_DATA);

		lbm.registerReceiver(mMessageReceiver, filter);

		if(!(TextUtils.isEmpty(answerStr))){
			if(!(TextUtils.isEmpty(AppConstant.testUUID))){
				checkUserSubjectAnswer(this,AppConstant.courseCode,AppConstant.chapterCode,answerStr,AppConstant.testUUID);
			}
		}
	}
	private void initView(){
		gv = (NoScrollGridView) findViewById(R.id.gridview);
		tv_timer_result = (TextView) findViewById(R.id.tv_timer_result);
		tv_paper_score = (TextView) findViewById(R.id.tv_paper_score);
		tv_exercise_again = (TextView) findViewById(R.id.tv_exercise_again);
		btn_back = findViewById(R.id.rl_back);

	}
	private void initData(){
		mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
		tv_timer_result.setText(Utils.timeToFomart(Integer.valueOf(totalTime))+"\n用时");
		tv_btn_back  = (TextView) findViewById(R.id.tv_btn_back);

		tv_btn_back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				finish();
			}
		});
		tv_exercise_again.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Intent intent = new Intent(ScantronItemActivity.this,IntroduceItemActivity.class);
				startActivity(intent);
				finish();
			}
		});
		btn_back.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View view) {
				finish();
			}
		});

	}
	private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			if (intent.getAction().equals(AppConstant.ACTION_EVENT_UPDATA_DATA)) {
				adapter.notifyDataSetChanged();
			}
		}
	};

	@Override
	protected void onDestroy() {
		super.onDestroy();
		LocalBroadcastManager.getInstance(this).unregisterReceiver(
				mMessageReceiver);
	}

	private class MyAdapter extends BaseAdapter {
		private Context mContext;
		private JSONArray jArray;

		public MyAdapter(Context context, JSONArray jsonArray) {
			this.mContext = context;
			this.jArray = jsonArray;
		}

		@Override
		public int getCount() {
			return answerResult.length();
		}

		@Override
		public Object getItem(int i) {
			return null;
		}

		@Override
		public long getItemId(int i) {
			return 0;
		}


		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			//mParent = parent;
			View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.exercise_item_option,parent,false);

			TextView tv = v.findViewById(R.id.tv_got_index);
			tv.setText(position+1+"");
			try {
				TextView tv2 = v.findViewById(R.id.tv_got_result);
				if ("对".equals(answerResult.get(position).toString())) {
					tv2.setBackgroundResource(R.drawable.tv_item_result_bg2);
					tv2.setText("正确");
				} else {
					tv2.setBackgroundResource(R.drawable.tv_item_result_bg);
					tv2.setText("错误");
				}
			}catch (Exception e){
				e.toString();
			}
			return v;
	}
	}


	//提交测试题答案
	public void checkUserSubjectAnswer(Context context,
									   String courseCode,String chapterCode,String answerStr,String testUUID){
		OkHttpUtils.getInstance(context).getJsonForString(OkHttpUtils.BASE_URL + "/appCourseSubject/checkUserSubjectAnswer2",
				new String[]{"courseCode","chapterCode","answerStr","testUUID"}, new String[]{courseCode,chapterCode,answerStr,testUUID}, new OkHttpUtils.HttpCallBack() {
					@Override
					public void onSuccess(String obj) {
						try {
							JSONObject jObject = new JSONObject(obj);
							if (0 == jObject.getInt("code")) {
								LogUtil.e("Forget", "在线测试-测试中——提交测试题答案成功");
								getAnswer(obj);
							} else {
								LogUtil.e("Forget", "在线测试-测试中——提交测试题答案失败");
							}
						} catch (Exception e) {
							e.toString();
						}
					}

					@Override
					public void onSuccess(JSONObject obj) {
						//resultListener.onSuccess(obj.toString());
					}

					@Override
					public void onError(String msg) {
						LogUtil.e("Forget", "在线测试-测试中——提交测试题答案失败");
					}
				});
	}
	public  Double allcurScore = 0.0, alltotalScore = 0.0;
	public JSONArray answerResult;
	private void getAnswer(String data){
		try {
			JSONObject jObject = new JSONObject(data);
			JSONArray jArray = jObject.getJSONArray("data");

			if (jArray.length() > 0) {
				JSONObject job = jArray.getJSONObject(0);
				allcurScore = job.getDouble("curScore");
				alltotalScore = job.getDouble("totalScore");
				answerResult = job.getJSONArray("result");

				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						tv_paper_score.setText("本次测试得分\n "+allcurScore+"分");
						adapter = new MyAdapter(ScantronItemActivity.this,answerResult);
						gv.setAdapter(adapter);
						gv.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent, View view,
													int position, long id) {
							}
						});
					}
				});


			}

		} catch (Exception e) {
			e.toString();
		}
	}
}